import React, { useState, useEffect } from 'react';
import { 
  Container, 
  Grid, 
  CssBaseline, 
  Paper,
  Tabs,
  Tab,
  Box,
  Typography,
  Avatar,
  Divider,
  Button,
  TextField,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Card,
  CardContent,
  CardMedia,
  Chip,
  InputAdornment,
  IconButton,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  CircularProgress,
  Snackbar,
  Alert
} from '@mui/material';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import Navbar from '../components/Navbar';
import SearchIcon from '@mui/icons-material/Search';
import {
  getCommunityPosts,
  getPostById,
  createPost,
  searchPosts,
  getHotTags,
  getCommunityAnnouncements,
  getFeaturedPosts,
  likePost,
  unlikePost
} from '../api/community';
import { navigationItems } from '../App';

// 模拟社区帖子数据
const communityPosts = [
  {
    id: 1,
    title: '求助：下载速度特别慢怎么解决？',
    content: '最近下载种子速度特别慢，有没有大佬能分享一下提速的经验？',
    author: '新手小白',
    avatar: 'https://i.pravatar.cc/150?img=1',
    date: '2024-05-01',
    // likes: 12,
    comments: 4,
    tags: ['求助', '下载问题']
  },
  {
    id: 2,
    title: '分享：最近看了部超赞的电影！',
    content: '最近看了《沙丘2》，画面和剧情都非常震撼，强烈推荐给大家！',
    author: '影视达人',
    avatar: 'https://i.pravatar.cc/150?img=2',
    date: '2024-04-30',
    // likes: 45,
    comments: 3,
    tags: ['影视分享', '推荐']
  },
  {
    id: 3,
    title: '活动：五一假期种子分享大会',
    content: '五一假期来临，站内将举办种子分享活动，上传优质资源可获得额外积分奖励！',
    author: '站长小李',
    avatar: 'https://i.pravatar.cc/150?img=3',
    date: '2024-04-29',
    // likes: 89,
    comments: 3,
    tags: ['官方活动', '积分奖励']
  },
  {
    id: 4,
    title: '讨论：大家都用什么下载软件？',
    content: '想了解下大家都用什么下载工具，qBittorrent和Transmission哪个更好用？',
    author: '技术宅',
    avatar: 'https://i.pravatar.cc/150?img=4',
    date: '2024-04-28',
    // likes: 32,
    comments: 4,
    tags: ['讨论', '下载工具']
  },
  {
    id: 5,
    title: '我是？',
    content: '你是？',
    author: '技术宅',
    avatar: 'https://i.pravatar.cc/150?img=4',
    date: '2024-04-28',
    // likes: 32,
    // comments: 47,
    tags: ['讨论', '下载工具']
  },
  {
    id: 6,
    title: 'asd',
    content: 'sfsadsad',
    author: '技术宅',
    avatar: 'https://i.pravatar.cc/150?img=4',
    date: '2024-04-28',
    // likes: 32,
    // comments: 47,
    tags: ['讨论', '下载工具']
  },
  {
    id: 7,
    title: 'test',
    content: 'test',
    author: '技术宅',
    avatar: 'https://i.pravatar.cc/150?img=4',
    date: '2024-04-28',
    // likes: 32,
    // comments: 47,
    tags: ['讨论', '下载工具']
  },
  {
    id: 8,
    title: '123',
    content: '23412',
    author: '技术宅',
    avatar: 'https://i.pravatar.cc/150?img=4',
    date: '2024-04-28',
    // likes: 32,
    // comments: 47,
    tags: ['讨论', '下载工具']
  },
];


function Community() {
  const location = useLocation();
  const navigate = useNavigate();
  
  // 状态管理
  const [posts, setPosts] = useState([]);
  const [hotTagsList, setHotTagsList] = useState([]);
  const [announcements, setAnnouncements] = useState([]);
  const [featuredPosts, setFeaturedPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [postTitle, setPostTitle] = useState('');
  const [postContent, setPostContent] = useState('');
  const [postTags, setPostTags] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [searchFilter, setSearchFilter] = useState('all');
  const [isSearching, setIsSearching] = useState(false);
  const [displayedPosts, setDisplayedPosts] = useState([]);
  const [isSearchMode, setIsSearchMode] = useState(false);
  const [error, setError] = useState(null);
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: '',
    severity: 'success'
  });
  
  // 获取社区帖子
  const fetchPosts = async () => {
    try {
      setLoading(true);
      const response = await getCommunityPosts();
      if (response && response.data) {
        setPosts(response.data);
        setDisplayedPosts(response.data);
      }
    } catch (error) {
      console.error('获取帖子失败:', error);
      setError('获取帖子失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };
  
  // 获取热门标签
  const fetchHotTags = async () => {
    try {
      const response = await getHotTags();
      if (response && response.data) {
        setHotTagsList(response.data);
      }
    } catch (error) {
      console.error('获取热门标签失败:', error);
    }
  };
  
  // 获取社区公告
  const fetchAnnouncements = async () => {
    try {
      const response = await getCommunityAnnouncements();
      if (response && response.data) {
        setAnnouncements(response.data);
      }
    } catch (error) {
      console.error('获取社区公告失败:', error);
    }
  };
  
  // 获取精华帖子
  const fetchFeaturedPosts = async () => {
    try {
      const response = await getFeaturedPosts();
      if (response && response.data) {
        setFeaturedPosts(response.data);
      }
    } catch (error) {
      console.error('获取精华帖子失败:', error);
    }
  };
  
  // 初始化数据
  useEffect(() => {
    fetchPosts();
    fetchHotTags();
    fetchAnnouncements();
    fetchFeaturedPosts();
  }, []);
  
  // 初始化时从URL获取搜索参数
  useEffect(() => {
    const urlParams = new URLSearchParams(location.search);
    const queryParam = urlParams.get('query');
    const filterParam = urlParams.get('filter');
    
    if (queryParam) {
      setSearchQuery(queryParam);
      setSearchFilter(filterParam || 'all');
      executeSearch(queryParam, filterParam || 'all');
    }
  }, [location.search]);
  
  // 处理发帖
  const handlePostSubmit = async () => {
    if (!postTitle.trim()) {
      setSnackbar({
        open: true,
        message: '请输入帖子标题',
        severity: 'error'
      });
      return;
    }
    
    if (!postContent.trim()) {
      setSnackbar({
        open: true,
        message: '请输入帖子内容',
        severity: 'error'
      });
      return;
    }
    
    try {
      setLoading(true);
      const tagsArray = postTags.split(',')
        .map(tag => tag.trim())
        .filter(tag => tag !== '');
      
      const id = localStorage.getItem("id");
    
      
        // 调用 createPost 函数，发送数据到后端
      const postData = {
        parentId: null, // 如果是新帖子，parentId 设为 null
        title: postTitle,
        content: postContent,
        userId: id, // 使用解码后的用户ID
        username: postTitle, // 使用解码后的用户名
        createTime: new Date().toISOString(),
        replyTime: new Date().toISOString(),
      };
      
      const response = await createPost(postData);
      
      if (response && response.data) {
        setSnackbar({
          open: true,
          message: '发布成功！',
          severity: 'success'
        });
        
        // 重置表单
        setPostTitle('');
        setPostContent('');
        setPostTags('');
        
        // 刷新帖子列表
        fetchPosts();
      }
    } catch (error) {
      console.error('发布帖子失败:', error);
      setSnackbar({
        open: true,
        message: '发布失败，请稍后重试',
        severity: 'error'
      });
    } finally {
      setLoading(false);
    }
  };
  
  // 执行搜索
  const executeSearch = async (query, filter) => {
    if (!query.trim()) {
      setDisplayedPosts(posts);
      setIsSearchMode(false);
      return;
    }
    
    try {
      setIsSearching(true);
      const response = await searchPosts(query, filter);
      
      if (response && response.data) {
        setDisplayedPosts(response.data);
        setIsSearchMode(true);
      }
    } catch (error) {
      console.error('搜索失败:', error);
      setSnackbar({
        open: true,
        message: '搜索失败，请稍后重试',
        severity: 'error'
      });
    } finally {
      setIsSearching(false);
    }
  };
  
  // 处理搜索
  const handleSearch = () => {
    // 更新URL参数以支持分享搜索结果
    const params = new URLSearchParams();
    if (searchQuery.trim()) {
      params.set('query', searchQuery);
      params.set('filter', searchFilter);
      navigate(`${location.pathname}?${params.toString()}`);
    }
    
    executeSearch(searchQuery, searchFilter);
  };
  
  // 清除搜索
  const clearSearch = () => {
    setSearchQuery('');
    setSearchFilter('all');
    setIsSearchMode(false);
    setDisplayedPosts(posts);
    navigate(location.pathname); // 清除URL参数
  };
  
  // 处理点赞
  const handleLike = async (postId, isLiked) => {
    try {
      if (isLiked) {
        await unlikePost(postId);
      } else {
        await likePost(postId);
      }
      
      // 更新帖子列表中的点赞状态
      const updatedPosts = posts.map(post => {
        if (post.id === postId) {
          return {
            ...post,
            isLiked: !isLiked,
            likes: isLiked ? post.likes - 1 : post.likes + 1
          };
        }
        return post;
      });
      
      setPosts(updatedPosts);
      
      // 如果在搜索模式下，也更新显示的帖子
      if (isSearchMode) {
        const updatedDisplayedPosts = displayedPosts.map(post => {
          if (post.id === postId) {
            return {
              ...post,
              isLiked: !isLiked,
              likes: isLiked ? post.likes - 1 : post.likes + 1
            };
          }
          return post;
        });
        
        setDisplayedPosts(updatedDisplayedPosts);
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      setSnackbar({
        open: true,
        message: '操作失败，请稍后重试',
        severity: 'error'
      });
    }
  };
  
  // 关闭提示
  const handleCloseSnackbar = () => {
    setSnackbar({ ...snackbar, open: false });
  };
  
  // 格式化日期
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  };
  
  return (
    <div className="App">
      <CssBaseline />
      <Navbar />
      
      <Container maxWidth="false" sx={{ mt: 3 }}>
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          <Tabs 
            value={location.pathname}
            indicatorColor="primary"
            textColor="primary"
            variant="scrollable"
            scrollButtons="auto"
          >
            {navigationItems.map((item) => (
              <Tab
                key={item.path}
                label={item.label}
                value={item.path}
                component={Link}
                to={item.path}
                sx={{ 
                  minWidth: 100,
                  '&.Mui-selected': { fontWeight: 'bold' }
                }}
              />
            ))}
          </Tabs>
        </Box>
      </Container>

      <Container maxWidth="false" sx={{ paddingTop: 3 }}>
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>

          {/* 搜索区域 */}
          <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            {/* <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <TextField
                fullWidth
                placeholder="搜索社区内容..."
                variant="outlined"
                size="medium"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') handleSearch();
                }}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      {isSearching ? (
                        <CircularProgress size={24} />
                      ) : (
                        <IconButton onClick={handleSearch} edge="end">
                          <SearchIcon />
                        </IconButton>
                      )}
                    </InputAdornment>
                  ),
                }}
              />
              <FormControl sx={{ minWidth: 150 }}>
                <InputLabel id="search-filter-label">筛选</InputLabel>
                <Select
                  labelId="search-filter-label"
                  id="search-filter"
                  value={searchFilter}
                  label="筛选"
                  onChange={(e) => setSearchFilter(e.target.value)}
                >
                  <MenuItem value="all">全部内容</MenuItem>
                  <MenuItem value="title">仅标题</MenuItem>
                  <MenuItem value="content">仅内容</MenuItem>
                  <MenuItem value="author">作者</MenuItem>
                  <MenuItem value="tag">标签</MenuItem>
                </Select>
              </FormControl>
              <Button
                variant="contained"
                color="primary"
                onClick={handleSearch}
                disabled={isSearching}
              >
                搜索
              </Button>
            </Box> */}
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mt: 2 }}>
              <Typography variant="body2" color="text.secondary" sx={{ mr: 1 }}>
                热门搜索:
              </Typography>
              {hotTagsList.slice(0, 4).map((tag, index) => (
                <Chip 
                  key={index}
                  label={tag.name}
                  size="small"
                  variant="outlined"
                  clickable
                  onClick={() => {
                    setSearchQuery(tag.name);
                    setSearchFilter('tag');
                    setTimeout(() => handleSearch(), 0);
                  }}
                  sx={{ borderRadius: 1 }}
                />
              ))}
            </Box>
          </Paper>

          {/* 发帖区域 */}
          {!isSearchMode && (
            <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
              <Typography variant="h5" gutterBottom>发表新帖</Typography>
              <TextField
                fullWidth
                placeholder="标题"
                variant="outlined"
                value={postTitle}
                onChange={(e) => setPostTitle(e.target.value)}
                sx={{ mb: 2 }}
              />
              <TextField
                fullWidth
                multiline
                rows={4}
                placeholder="有什么想法？在这里分享..."
                variant="outlined"
                value={postContent}
                onChange={(e) => setPostContent(e.target.value)}
                sx={{ mb: 2 }}
              />
              <TextField
                fullWidth
                placeholder="标签（用逗号分隔，如：求助,下载问题）"
                variant="outlined"
                value={postTags}
                onChange={(e) => setPostTags(e.target.value)}
                sx={{ mb: 2 }}
              />
              <Button 
                variant="contained" 
                color="primary" 
                onClick={handlePostSubmit}
                disabled={!postTitle.trim() || !postContent.trim() || loading}
              >
                {loading ? '发布中...' : '发布帖子'}
              </Button>
            </Paper>
          )}

          {/* 主要内容区域 */}
          <Grid container spacing={3} sx={{ position: 'relative' }}>
            {/* 左侧：帖子列表 */}
            <Grid item xs={12} md={8}>
              <Paper elevation={3} sx={{ p: 3, minHeight: '500px', width: '100%', boxSizing: 'border-box' }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                  <Typography variant="h5">
                    {isSearchMode 
                      ? `搜索结果 (${displayedPosts.length})` 
                      : '社区动态'
                    }
                  </Typography>
                  {isSearchMode && (
                    <Button
                      variant="outlined"
                      size="small"
                      onClick={clearSearch}
                    >
                      清除搜索
                    </Button>
                  )}
                </Box>
                
                {loading ? (
                  <Box sx={{ display: 'flex', justifyContent: 'center', py: 5 }}>
                    <CircularProgress />
                  </Box>
                ) : error ? (
                  <Box sx={{ py: 5, textAlign: 'center' }}>
                    <Typography variant="h6" color="error">
                      {error}
                    </Typography>
                    <Button 
                      variant="contained" 
                      color="primary"
                      onClick={fetchPosts}
                      sx={{ mt: 2 }}
                    >
                      重试
                    </Button>
                  </Box>
                ) : displayedPosts.length > 0 ? (
                  <Box sx={{ maxHeight: '800px', overflow: 'auto', width: '100%' }}>
                    {displayedPosts.map((post) => (
                      <Card key={post.id} sx={{ 
                        mb: 3, 
                        borderRadius: 2, 
                        transition: '0.3s', 
                        '&:hover': { boxShadow: 6 },
                        width: '100%',
                        boxSizing: 'border-box'
                      }}>
                        <CardContent>
                          <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                            <Avatar 
                              src={post.authorAvatar} 
                              sx={{ 
                                mr: 2, 
                                cursor: 'pointer',
                                '&:hover': { opacity: 0.8 }
                              }}
                              onClick={() => navigate(`/profile?user=${post.authorId}`)}
                            />
                            <Box>
                              <Typography 
                                variant="subtitle1" 
                                sx={{ 
                                  cursor: 'pointer',
                                  '&:hover': { color: 'primary.main' }
                                }}
                                onClick={() => navigate(`/profile?user=${post.authorId}`)}
                              >
                                {post.authorName}
                              </Typography>
                              <Typography variant="caption" color="text.secondary">
                                {formatDate(post.createTime)}
                              </Typography>
                            </Box>
                          </Box>
                          
                          <Typography variant="h6" gutterBottom>
                            {post.title}
                          </Typography>
                          <Typography 
                            variant="body2" 
                            color="text.secondary" 
                            paragraph
                            sx={{
                              display: '-webkit-box',
                              WebkitLineClamp: 3,
                              WebkitBoxOrient: 'vertical',
                              overflow: 'hidden',
                              textOverflow: 'ellipsis'
                            }}
                          >
                            {post.content}
                          </Typography>
                          
                          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 2 }}>
                            {post.tags && post.tags.map((tag, index) => (
                              <Chip 
                                key={index} 
                                label={tag} 
                                size="small"
                                variant="outlined"
                                sx={{ borderRadius: 1 }}
                                clickable
                                onClick={() => {
                                  setSearchQuery(tag);
                                  setSearchFilter('tag');
                                  setTimeout(() => handleSearch(), 0);
                                }}
                              />
                            ))}
                          </Box>
                          
                          <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                            <Typography variant="body2" color="text.secondary">
                              <span 
                                style={{ 
                                  cursor: 'pointer', 
                                  color: post.isLiked ? '#1976d2' : 'inherit'
                                }}
                                onClick={() => handleLike(post.id, post.isLiked)}
                              >
                                👍 {post.likes} 赞同
                              </span> • 💬 {post.comments} 评论
                            </Typography>
                            <Button 
                              size="small" 
                              color="primary"
                              component={Link}
                              to={`/post/${post.id}`}
                            >
                              查看详情
                            </Button>
                          </Box>
                        </CardContent>
                      </Card>
                    ))}
                  </Box>
                ) : (
                  <Box sx={{ py: 5, textAlign: 'center' }}>
                    <Typography variant="h6" color="text.secondary">
                      {isSearchMode ? '未找到匹配的帖子' : '暂无帖子'}
                    </Typography>
                    <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                      {isSearchMode ? '尝试使用其他关键词或调整筛选条件' : '成为第一个发帖的人吧！'}
                    </Typography>
                  </Box>
                )}
              </Paper>
            </Grid>
            
            {/* 右侧：社区信息 */}
            <Grid item xs={12} md={4}>
              <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>社区公告</Typography>
                {announcements.length > 0 ? (
                  <>
                    {announcements.slice(0, 1).map((notice, index) => (
                      <Box key={index}>
                        <Typography variant="subtitle1" fontWeight="bold">
                          {notice.noticeTopic}
                        </Typography>
                        <Typography variant="body2" paragraph>
                          {notice.content}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          发布时间：{formatDate(notice.createTime)}
                        </Typography>
                      </Box>
                    ))}
                    {announcements.length > 1 && (
                      <Button 
                        variant="text" 
                        size="small" 
                        sx={{ mt: 1 }}
                        onClick={() => navigate('/announcements')}
                      >
                        查看更多公告 ({announcements.length})
                      </Button>
                    )}
                  </>
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    暂无公告
                  </Typography>
                )}
              </Paper>
              
              <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>热门标签</Typography>
                <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                  {hotTagsList.map((tag, index) => (
                    <Chip 
                      key={index} 
                      label={`${tag.name} (${tag.count})`} 
                      variant="outlined"
                      sx={{ mb: 1, borderRadius: 1 }}
                      clickable
                      onClick={() => {
                        setSearchQuery(tag.name);
                        setSearchFilter('tag');
                        // 更新URL参数以支持分享搜索结果
                        const params = new URLSearchParams();
                        params.set('query', tag.name);
                        params.set('filter', 'tag');
                        navigate(`${location.pathname}?${params.toString()}`);
                        executeSearch(tag.name, 'tag');
                      }}
                    />
                  ))}
                </Box>
              </Paper>
              
              <Paper elevation={3} sx={{ p: 3 }}>
                <Typography variant="h6" gutterBottom>社区精华</Typography>
                {featuredPosts.length > 0 ? (
                  <List>
                    {featuredPosts.map((post, index) => (
                      <React.Fragment key={post.id}>
                        <ListItem 
                          sx={{ px: 0 }}
                          component={Link}
                          to={`/post/${post.id}`}
                          style={{ textDecoration: 'none', color: 'inherit' }}
                        >
                          <ListItemText 
                            primary={post.title} 
                            secondary={`by ${post.authorName} • 精华帖 • ${post.viewCount || 0}次浏览`} 
                          />
                        </ListItem>
                        {index < featuredPosts.length - 1 && <Divider component="li" />}
                      </React.Fragment>
                    ))}
                  </List>
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    暂无精华帖子
                  </Typography>
                )}
              </Paper>
            </Grid>
          </Grid>
        </Box>
      </Container>
      
      {/* 提示信息 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert 
          onClose={handleCloseSnackbar} 
          severity={snackbar.severity} 
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </div>
  );
}

export default Community; 